package com.itheima.reggie.service.impl;

import cn.hutool.core.util.IdUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.itheima.reggie.common.CustomException;
import com.itheima.reggie.common.ResultInfo;
import com.itheima.reggie.domain.Category;
import com.itheima.reggie.mapper.CategoryMapper;
import com.itheima.reggie.service.CategoryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

/**
 * @author zsk
 * @create 2022-02-14-10:54
 */
@Service//把此类作为对象放入到容器中
public class CategoryServiceImpl implements CategoryService {

    //依赖注入
    @Autowired
    private CategoryMapper categoryMapper;

    //查询所有
    @Override
    public List<Category> findAll() {
        //调用mapper层查询
        return categoryMapper.findAll();
    }

    //添加数据
    @Override
    public void save(Category category) {
        //补全数据
        category.setId(IdUtil.getSnowflake(1,1).nextId());
//        category.setCreateTime(new Date());
//        category.setUpdateTime(new Date());
//        category.setCreateUser(1L);//todo 临时写死
//        category.setUpdateUser(1L);//todo 临时写死

        //调用mapper层添加
        categoryMapper.save(category);
    }

    //修改数据
    @Override
    public void update(Category category) {
        //更新修改人与修改参数
//        category.setUpdateUser(1L);
//        category.setUpdateTime(new Date());//todo 临时写死

        //调用mapper层修改
        categoryMapper.updateById(category);
    }

    //删除数据
    @Override
    public ResultInfo delete(Long id) {
        //接受菜品类中数据，如果>0，不允许删除
        Integer count1 = categoryMapper.countDishByCategoryId(id);
        if (count1 > 0){
            throw new CustomException("当前分类下存在菜品，不允许删除");
        }

        //接受套餐类中数据，如果>0，不允许删除
        Integer count2 = categoryMapper.countSetmealByCategoryId(id);
        if (count2 > 0){
            throw new CustomException("当前分类下存在套餐,不允许删除");
        }
        //正常删除数据
        categoryMapper.delete(id);

        //返回成功标识
        return ResultInfo.success(null);
    }

    @Override
    public List<Category> findList(Integer type) {

        //设置查询条件
        LambdaQueryWrapper<Category> wrapper = new LambdaQueryWrapper<>();
        //相当于 where type = #{type}
        wrapper.eq(Category::getType,type);

        //调用mapper层查询并返回
        return categoryMapper.selectList(wrapper);
    }
}
